package top.cardone.web.servlet;

import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.CharEncoding;
import org.springframework.web.servlet.ModelAndView;
import top.cardone.context.util.CodeExceptionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Writer;
import java.util.Map;

/**
 * Created by yao hai tao on 2016/1/20.
 */
@Log4j2
public class HandlerExceptionResolver implements org.springframework.web.servlet.HandlerExceptionResolver {
    @Setter
    private String errorViewName = "error.ftl";

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        log.error(ex.getMessage(), ex);

        String servletPath = request.getServletPath();

        if (!org.apache.commons.lang3.StringUtils.startsWith(request.getContentType(), org.springframework.http.MediaType.APPLICATION_JSON_VALUE)) {
            ModelAndView model = new ModelAndView(this.errorViewName);

            Map<String, String> errorInfoMap = CodeExceptionUtils.newMap(servletPath, ex);

            model.addAllObjects(errorInfoMap);

            return model;
        }

        response.setCharacterEncoding(CharEncoding.UTF_8);
        response.setContentType(org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE);

        try (Writer out = response.getWriter()) {
            String json = CodeExceptionUtils.newString(servletPath, ex);

            out.write(json);

            out.flush();
        } catch (java.io.IOException e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }
}
